# -*- coding:utf-8 -*-
# 向onenet平台已经创建的数据流发送数据点
import urllib.request
import json
import time
import datetime
import RPi.GPIO as GPIO

# GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

# set GPIO Pins
GPIO_TRIGGER = 2
GPIO_ECHO = 3

# set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

APIKEY = 'wss3GsBfjea=JFf9KB0rPIJxgVg='  #改成你的APIKEY,需要在设备里创建


def get_distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)

    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()

    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2

    return distance


def http_post():
    dist = get_distance()  # get current temperature
    print(dist)
    CurTime = datetime.datetime.now()  # get current time
    url = 'http://api.heclouds.com/devices/921297084/datapoints'
    values = {
        'datastreams': [{
            "id":
            "distance",
            "datapoints": [{
                "at": CurTime.isoformat(),
                "value": dist
            }]
        }]
    }
    jdata = json.dumps(values)  # convert data to json format
    print("\n=== send data ===")
    print(jdata)
    data = bytes(jdata, 'utf-8')
    request = urllib.request.Request(url, data)
    request.add_header('api-key', APIKEY)
    request.get_method = lambda: 'POST'
    request = urllib.request.urlopen(request)
    return request.read()


if __name__ == "__main__":
    while True:
        time.sleep(1)
        resp = http_post()
        print("=== recv data ===")
        print(resp)
        time.sleep(1)
